import React, { useState, useEffect } from 'react';
import { Card, Spin, message, Tag, Descriptions, Button, Modal, Typography, Divider, Table } from 'antd';
import { CopyOutlined, ExpandOutlined, ReloadOutlined } from '@ant-design/icons';
import { judgeApi } from '../../api/services/Judge/judgeApi';
import type { Judge, JudgeResultResponse } from '../../api/vo/judge';
import './SubmissionDetail.less';

const { Text, Paragraph } = Typography;

interface SubmissionDetailProps {
  submitId: number;
  visible?: boolean;
  onClose?: () => void;
}

const SubmissionDetail: React.FC<SubmissionDetailProps> = ({ 
  submitId, 
  visible = true,
  onClose 
}) => {
  const [loading, setLoading] = useState(false);
  const [judgeDetail, setJudgeDetail] = useState<Judge | null>(null);
  const [codeModalVisible, setCodeModalVisible] = useState(false);

  // 获取提交详情
  const fetchSubmissionDetail = async () => {
    if (!submitId) return;
    
    setLoading(true);
    try {
      const response: JudgeResultResponse = await judgeApi.getJudgeResult(submitId);
      
      if (response.code === 200 && response.data) {
        setJudgeDetail(response.data);
      } else {
        message.error(response.message || '获取提交详情失败');
      }
    } catch (error) {
      console.error('获取提交详情失败:', error);
      message.error('获取提交详情失败');
    } finally {
      setLoading(false);
    }
  };

  // 组件挂载时获取数据
  useEffect(() => {
    if (visible && submitId) {
      fetchSubmissionDetail();
    }
  }, [submitId, visible]);

  // 刷新数据
  const handleRefresh = () => {
    fetchSubmissionDetail();
  };

  // 复制代码到剪贴板
  const copyCodeToClipboard = () => {
    if (!judgeDetail?.code) {
      message.warning('没有可复制的代码内容');
      return;
    }
    
    navigator.clipboard.writeText(judgeDetail.code).then(
      () => {
        message.success('代码已复制到剪贴板');
      },
      () => {
        message.error('复制失败，请手动复制');
      }
    );
  };

  // 渲染判题结果标签
  const renderJudgeResult = (result: number) => {
    const resultMap: Record<number, { text: string; color: string }> = {
      [-1]: { text: '失败', color: '#f5222d' },
      [0]: { text: 'CE', color: '#fa8c16' },
      [1]: { text: 'AC', color: '#52c41a' },
      [2]: { text: 'WA', color: '#f5222d' },
      [3]: { text: 'TLE', color: '#fa541c' },
      [4]: { text: 'MLE', color: '#722ed1' },
      [5]: { text: 'PE', color: '#13c2c2' },
      [6]: { text: 'RE', color: '#eb2f96' },
      [7]: { text: 'SE', color: '#595959' }
    };
    
    const resultInfo = resultMap[result] || { text: '未知', color: '#d9d9d9' };
    return <Tag color={resultInfo.color}>{resultInfo.text}</Tag>;
  };

  // 渲染判题状态标签
  const renderJudgeStatus = (status: number) => {
    const statusMap: Record<number, { text: string; color: string }> = {
      [0]: { text: '等待中', color: '#faad14' },
      [1]: { text: '判题中', color: '#1890ff' },
      [2]: { text: '成功', color: '#52c41a' },
      [3]: { text: '失败', color: '#f5222d' }
    };
    
    const statusInfo = statusMap[status] || { text: '未知', color: '#d9d9d9' };
    return <Tag color={statusInfo.color}>{statusInfo.text}</Tag>;
  };

  // 渲染语言标签
  const renderLanguage = (language: string) => {
    const languageColors: Record<string, string> = {
      'JAVA': '#f56a00',
      'CPP': '#2f54eb',
      'C': '#722ed1',
      'PYTHON': '#52c41a',
      'JAVASCRIPT': '#faad14'
    };
    
    return (
      <Tag color={languageColors[language] || '#108ee9'}>
        {language}
      </Tag>
    );
  };


  return (
    <Card 
      className="submission-detail"
      title={`提交详情 - ID: ${submitId}`}
      extra={
        <div>
          <Button 
            icon={<ReloadOutlined />} 
            onClick={handleRefresh}
            loading={loading}
            style={{ marginRight: 8 }}
          >
            刷新
          </Button>
          {onClose && (
            <Button onClick={onClose}>
              关闭
            </Button>
          )}
        </div>
      }
      loading={loading}
    >
      {judgeDetail ? (
        <div>
          <Descriptions bordered column={2} size="small">
            <Descriptions.Item label="提交ID">{judgeDetail.submitId}</Descriptions.Item>
            <Descriptions.Item label="用户ID">{judgeDetail.userId}</Descriptions.Item>
            <Descriptions.Item label="题目ID">{judgeDetail.pid}</Descriptions.Item>
            <Descriptions.Item label="题目标题">{judgeDetail.title || '-'}</Descriptions.Item>
            <Descriptions.Item label="判题状态">
              {renderJudgeStatus(judgeDetail.status)}
            </Descriptions.Item>
            <Descriptions.Item label="判题结果">
              {renderJudgeResult(judgeDetail.result)}
            </Descriptions.Item>
            <Descriptions.Item label="编程语言">
              {renderLanguage(judgeDetail.language)}
            </Descriptions.Item>
            <Descriptions.Item label="内存消耗">
              {judgeDetail.memory ? `${judgeDetail.memory} KB` : '-'}
            </Descriptions.Item>
            <Descriptions.Item label="时间消耗">
              {judgeDetail.time ? `${judgeDetail.time} ms` : '-'}
            </Descriptions.Item>
            <Descriptions.Item label="是否重判">
              <Tag color={judgeDetail.isRejudge ? '#fa8c16' : '#52c41a'}>
                {judgeDetail.isRejudge ? '是' : '否'}
              </Tag>
            </Descriptions.Item>
            <Descriptions.Item label="提交时间" span={2}>
              {new Date(judgeDetail.createTime).toLocaleString()}
            </Descriptions.Item>
            {judgeDetail.updateTime && (
              <Descriptions.Item label="更新时间" span={2}>
                {new Date(judgeDetail.updateTime).toLocaleString()}
              </Descriptions.Item>
            )}
          </Descriptions>

          {judgeDetail.msg && (
            <>
              <Divider orientation="left">判题信息</Divider>
              <Card className="judge-message-section" size="small">
                <pre style={{ margin: 0, whiteSpace: 'pre-wrap', wordBreak: 'break-all' }}>
                  {judgeDetail.msg}
                </pre>
              </Card>
            </>
          )}

  

          {judgeDetail.code && (
            <>
              <Divider orientation="left">提交代码</Divider>
              <Card 
                className="code-section"
                size="small" 
                extra={
                  <div>
                    <Button 
                      type="text" 
                      size="small" 
                      icon={<CopyOutlined />}
                      onClick={copyCodeToClipboard}
                    >
                      复制代码
                    </Button>
                    <Button 
                      type="text" 
                      size="small" 
                      icon={<ExpandOutlined />}
                      onClick={() => setCodeModalVisible(true)}
                    >
                      全屏查看
                    </Button>
                  </div>
                }
              >
                <pre style={{ 
                  margin: 0, 
                  whiteSpace: 'pre-wrap', 
                  wordBreak: 'break-all',
                  maxHeight: '300px',
                  overflow: 'auto',
                  backgroundColor: '#f5f5f5',
                  padding: '12px',
                  borderRadius: '4px'
                }}>
                  {judgeDetail.code}
                </pre>
              </Card>
            </>
          )}
        </div>
      ) : (
        <div className="empty-state">
          <Text type="secondary">暂无数据</Text>
        </div>
      )}

      {/* 代码全屏查看模态框 */}
      <Modal
        className="code-modal"
        title="提交代码"
        open={codeModalVisible}
        onCancel={() => setCodeModalVisible(false)}
        footer={[
          <Button key="copy" icon={<CopyOutlined />} onClick={copyCodeToClipboard}>
            复制代码
          </Button>,
          <Button key="close" onClick={() => setCodeModalVisible(false)}>
            关闭
          </Button>
        ]}
        width="90%"
        style={{ top: 20 }}
      >
        <pre style={{ 
          margin: 0, 
          whiteSpace: 'pre-wrap', 
          wordBreak: 'break-all',
          maxHeight: '70vh',
          overflow: 'auto',
          backgroundColor: '#f5f5f5',
          padding: '16px',
          borderRadius: '4px',
          fontSize: '14px',
          lineHeight: '1.5'
        }}>
          {judgeDetail?.code}
        </pre>
      </Modal>
    </Card>
  );
};

export default SubmissionDetail;